﻿package com.curlyben.utils {
	import flash.utils.ByteArray;
	
	/**
	* ...
	* @author Default
	*/
	public class Strings {
		
		public function Strings() {
			
		}
			
		public static function Reverse(string:String):String {
			var out:String = "";
			var chars:Array = string.split("");
			while (chars.length > 0)
				out += chars.pop();
			return out;
		}
		
		public static function PadLeft(string:String, char:String, length:uint):String {
			if (string.length > 32) return Reverse(Reverse(string).substr(0, 32));
			char = char.split("")[0];
			var out:String = char;
			while (out.length + string.length < 32)
				out += char;
			return out + string;
		}
		
		public static function PadRight(string:String, char:String, length:uint):String {
			if (string.length > 32) return string.substr(0, 32);
			char = char.split("")[0];
			while (string.length < 32)
				string += char;
			return string;
		}
		
		public static function UnicodeToUTF(bytes:ByteArray, offset:uint = 0, length:uint = 0xFFFFFFFF):String {
			length = length > bytes.length ? bytes.length : length;
			var op:uint = bytes.position;
			bytes.position = offset;
			var b:ByteArray = new ByteArray();
			var bom:uint = bytes.readUnsignedShort();
			var swap:Boolean;
			if (bom == 0xFFFE) {
				length -= 2;
				//swap
				while (length > 0) {
					bytes.position++;
					b.writeByte(bytes.readByte());
					bytes.position -= 2;
					b.writeByte(bytes.readByte());
					bytes.position++;
					length -= 2;
				}
			} else {
				if (bom !== 0xFEFF)
					bytes.position -= 2;
				else
					length -= 2;
				while (length > 0) {
					b.writeByte(bytes.readByte());
					length--;
				}
			}
			var out:ByteArray = new ByteArray();
			b.position = 0;
			while (b.bytesAvailable) {
				var c:uint = b.readUnsignedShort();
				if (c > 0x007F)
					out.writeShort(c);
				else
					out.writeByte(c);
			}
			out.position = 0;
			bytes.position = op;
			return out.readUTFBytes(out.length);
		}
		
		public static function TrimStart(string:String, char:String):String {
			var out:String = string;
			while (out.indexOf(char) == 0)
				out = out.substr(char.length);
			return out;
		}
		
		public static function TrimEnd(string:String, char:String):String {
			var out:String = Reverse(string);
			var rchar:String = Reverse(char);
			return Reverse(TrimStart(out, rchar));
		}
	}
}